package com.cmfi.controller;

import java.net.URISyntaxException;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.cmfi.domain.Equipment;
import com.cmfi.service.inter.EquipmentService;
import com.cmfi.utils.Code;
import com.cmfi.utils.Result;

import lombok.extern.slf4j.Slf4j;

//return都是result

@Slf4j
@RestController
@RequestMapping("/api/equipment")
public class EquipmentController {
    @Autowired
    private EquipmentService equipmentService;
    static Logger log = LoggerFactory.getLogger(EquipmentController.class);
    
    /**
     * {@code PUT  /read-mes/:id} : Updates an existing equipment.
     *
     * @param id the id of the readMe to save.
     * @param readMe the readMe to update.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated readMe,
     * or with status {@code 400 (Bad Request)} if the readMe is not valid,
     * or with status {@code 500 (Internal Server Error)} if the readMe couldn't be updated.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PutMapping("/equipment/{id}")
    @PreAuthorize("hasAuthority('equipment')")
	public Result updateEquipment(@PathVariable(value = "id", required = false) final Long id,
			@RequestBody Equipment equipment) {
		log.info("[EquipmentController][updateEquipment] equipment:{},", equipment);
		if (id == null) {
			return new Result(Code.UPDATE_ERR, "计划ID为空");
		}
		try {
			equipmentService.update(equipment, id);//调用对象！！！！！开头第一个字母小写！！！！！
			return new Result(Code.UPDATE_OK, equipment);
		} catch (Exception e) {
			log.error("[EquipmentController][updateEquipment] e,", e);
			return new Result(Code.UPDATE_ERR, e.getMessage());
		}
	}
    
    /**
     * {@code GET  /read-mes} : get all the equipments.
     *
     * @param findByPage the pagination information.
     * @param request a {@link ServerHttpRequest} request.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of readMes in body.
     */
    @GetMapping(value = "/equipments", produces = MediaType.APPLICATION_JSON_VALUE)
    @PreAuthorize("hasAuthority('equipment')")
	public Result getAllEquipments(@RequestParam Map<String, Object> params) {
		log.debug("REST request to get a page of Equipments.");
		List<Equipment> equipmentList = null;
		long total = 0;
		try {
			if (params == null) {
				return new Result(Code.GET_ERR, "入参为空");
			}
			long pageNum = 0;// 页数
			long pageSize = 0;// 一页有几个
			if (params.containsKey("pageNum")) {
				pageNum = Long.parseLong(params.get("pageNum").toString());// 强制转换成long型，因为Apifox不知道为啥传的总是String类型，会报错。
			}
			if (params.containsKey("pageSize")) {
				pageSize = Long.parseLong(params.get("pageSize").toString());
			}
			equipmentList = equipmentService.findByPage(pageNum, pageSize);
			total = equipmentList.size();
		} catch (Exception e) {
			log.error("[EquipmentController][getAllEquipments] e:{}", e);
			return new Result(Code.GET_ERR, e.getMessage());
		}
		return new Result(Code.GET_OK, equipmentList, total);
	}

//    /**
//     * {@code GET  /read-mes/:id} : get the "id" equipment.
//     *
//     * @param id the id of the readMe to retrieve.
//     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the readMe, or with status {@code 404 (Not Found)}.
//     */
//    @GetMapping("/equipment/{id}")
//    @PreAuthorize("hasAuthority('equipment')")
//    public Result getEquipment(@PathVariable Long id) {
//        log.debug("REST request to get Equipment : {}", id);
//        try {
//        	equipmentService.getById(id);
//		} catch (Exception e) {
//			log.error("[EquipmentController][getEquipment] id: {}", id);
//			return new Result(Code.GET_ERR, e.getMessage());
//		}
//		return new Result(Code.GET_OK, id);
//    }
    
    /**
     * {@code DELETE  /forklift-plans/:id} : delete the "id" Equipment.
     *
     * @param id the id of the readMe to delete.
     * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
     */
    @DeleteMapping("/equipment/{id}")
    @PreAuthorize("hasAuthority('equipment')")
	public Result deleteEquipment(@PathVariable Long id) {
    	log.debug("REST request to delete Equipment : {}", id);
		try {
			equipmentService.delete(id);
		} catch (Exception e) {
			log.error("[EquipmentController][deleteEquipment] id: {}", id);
			return new Result(Code.GET_ERR, e.getMessage());
		}
		return new Result(Code.DELETE_OK, id);
	}
     
    /**
     * Get the status of equipments.
     * @param id
     * @return
     */
    @GetMapping(value = "/allequipmentstatus", produces = MediaType.APPLICATION_JSON_VALUE)
    @PreAuthorize("hasAuthority('equipment')")
    public Result getEquipmentStatus(@RequestParam Map<String, Object> params) {
    	log.debug("REST request to get a page of Equipments' status.");
		List<Equipment> equipmentStatusList = null;
		long total = 0;
		try {
			if (params == null) {
				return new Result(Code.GET_ERR, "入参为空");
			}
			long pageNum = 0;// 页数
			long pageSize = 0;// 一页有几个
			if (params.containsKey("pageNum")) {
				pageNum = Long.parseLong(params.get("pageNum").toString());// 强制转换成long型，因为Apifox不知道为啥传的总是String类型，会报错。
			}
			if (params.containsKey("pageSize")) {
				pageSize = Long.parseLong(params.get("pageSize").toString());
			}
			equipmentStatusList = equipmentService.findByPageAndStatus(pageNum, pageSize);
			total = equipmentStatusList.size();
		} catch (Exception e) {
			log.error("[EquipmentController][getEquipmentStatus] e:{}", e);
			return new Result(Code.GET_ERR, e.getMessage());
		}
		return new Result(Code.GET_OK, equipmentStatusList, total);
    }
    
    /**
     * Get the warning messages of equipments.
     * @param id the id of the readMe to retrieve.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the Equipment, or with status {@code 404 (Not Found)}.
     */
    @GetMapping(value = "/allequipmentwarnings", produces = MediaType.APPLICATION_JSON_VALUE)
    @PreAuthorize("hasAuthority('equipment')")
    public Result getEquipmentWarnings(@RequestParam Map<String, Object> params) {
    	log.debug("REST request to get a page of Equipments' warnings.");
		List<Equipment> equipmentWarningsList = null;
		long total = 0;
		try {
			if (params == null) {
				return new Result(Code.GET_ERR, "入参为空");
			}
			long pageNum = 0;// 页数
			long pageSize = 0;// 一页有几个
			if (params.containsKey("pageNum")) {
				pageNum = Long.parseLong(params.get("pageNum").toString());// 强制转换成long型，因为Apifox不知道为啥传的总是String类型，会报错。
			}
			if (params.containsKey("pageSize")) {
				pageSize = Long.parseLong(params.get("pageSize").toString());
			}
			equipmentWarningsList = equipmentService.findByPageAndWarnings(pageNum, pageSize);
			total = equipmentWarningsList.size();
		} catch (Exception e) {
			log.error("[EquipmentController][getEquipmentWarnings] e:{}", e);
			return new Result(Code.GET_ERR, e.getMessage());
		}
		return new Result(Code.GET_OK, equipmentWarningsList, total);
    }
    
}

